package logview.mbeans;

import java.util.ArrayList;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectInstance;
import javax.management.ObjectName;

import logview.InitServlet;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringUtils;

public class LogFileManager implements LogFileManagerMBean {
	private MBeanServer server = null;
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogFileManager.class);
	
	@SuppressWarnings("unchecked")
	public LogFileManager() {
		ArrayList srv = MBeanServerFactory.findMBeanServer(InitServlet.agentId);
		if (srv!=null && srv.size()==1) {
			this.server = (MBeanServer) srv.get(0);
		}
	}
	
	public void addLogFile(String id, String logfile) {
		LogFile mbean = new LogFile();
		mbean.setFilename(logfile);
		mbean.setId(id);
		try {
			if (server==null)
				throw new NotImplementedException("MBeanServer not set in LogFileManagerMBean");
			server.registerMBean(mbean, ObjectName.getInstance(InitServlet.DOMAIN+":id="+id+",type="+LogFile.class.getName()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static ObjectName getObjectName() {
		try {
			return ObjectName.getInstance(InitServlet.DOMAIN+":id=LogFileManager,type="+LogFileManager.class.getName());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void addLogFile(String logfile) {
		String id = StringUtils.replaceChars(logfile, '/', '_');
		id = StringUtils.replaceChars(id, '.', '-');
		this.addLogFile(id, logfile);
	}

	@SuppressWarnings("unchecked")
	public Integer getLogCount() {
		int count = 0;
		Set mbeans = server.queryMBeans(null, null);
		for (Object on : mbeans) {
			ObjectInstance oi = ((ObjectInstance)on);
			// TODO use proper query
			if (oi.getClassName().endsWith(LogFile.class.getName())) {
				log.debug("classname: "+oi.getClassName()+"; objectname: "+oi.getObjectName());
				count++;
			}
		}
		log.debug("count: "+count);
		return new Integer(count);
	}
	
}
